import { ProtocolPool } from "./protobufs/base/BaseProtocol";

export default class GameNet {
    private static _instance: GameNet = null;
    static get instance() {
        if (!this._instance) {
            this._instance = new GameNet();
        }
        return this._instance;
    }
    static DISCONNECT_REASON_MULTI_LOGIN: string = "multi_login";
    static DISCONNECT_REASON_NORMAL: string = "normal";

    protocolPool: ProtocolPool = null;
    msgOperateMap: { [msgType: number]: Function } = {};

    constructor() {
        this.protocolPool = new ProtocolPool();
    }

    rigiserMsgOperate(msgType: number, recvFunc: Function) {
        this.msgOperateMap[msgType] = recvFunc;
    }

    onRecvMsg(msgType: number) {
        let operFunc = this.msgOperateMap[msgType];
        if (operFunc) {
            let protocol = ProtocolPool.instance.getProtocolByType(msgType);
            if (protocol) {
                protocol.decode();
                protocol.decodeCallBack && protocol.decodeCallBack(protocol);
                operFunc(protocol);
            } else {
                console.log(`unknow protocol: ${msgType}`);
            }
        } else {
            console.log(`unknow protocol: ${msgType}`);
        }
    }
}
